controller.controller('ChartIndexController',['$scope','$rootScope','$routeParams','serverService',function($scope,$rootScope,$routeParams,serverService){
    var serverId=$routeParams.serverId;
    serverService.getServers(function(serverResponse){
        var infoMap={};
        var servers=serverResponse.data;

        var updateInfoMap=function(callback){
            serverService.getInfos(function(response){
                infoMap[new Date().getTime()]=response.data;

                if(objectUtil.isNotNull(callback)) {
                    callback(response);
                }
            });
        };

        var getInfo=function(serverId,field){
            var result=[];

            for(var infoTime in infoMap) {
                var info=infoMap[infoTime][serverId];
                if(objectUtil.isNull(info)) {
                    continue;
                }

                var lines=info.split('\r\n');
                for(var i=0;i<lines.length;i++) {
                    var line=lines[i];
                    if(!stringUtil.startWith(line,field)) {
                        continue;
                    }

                    result.push(line.split(':')[1]);
                    break;
                }
            }

            return result;
        };

        var getChartOptions=function(title,field){
            var options= {
                animation: false,
                title: {
                    text: title
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        animation: false
                    }
                },
                legend:{
                    data:(function(){
                        var data=['总体'];

                        for(var i=0;i<servers.length;i++) {
                            data.push(servers[i].id);
                        }

                        return data;
                    })(),
                    selected:(function(){
                        var data={};
                        data['总体']=stringUtil.isBlank(serverId);

                        for(var i=0;i<servers.length;i++) {
                            var server=servers[i];
                            data[server.id]=(stringUtil.isBlank(serverId) || server.id==serverId)
                        }

                        return data;
                    })()
                },
                xAxis: {
                    type: 'category',
                    data: (function () {
                        var data = [];

                        for (info in infoMap) {
                            data.push(new Date(parseInt(info)).format('hh:mm:ss'));
                        }

                        return data;
                    })(),
                    splitLine: {
                        show: false
                    }
                },
                yAxis: [{
                    type: 'value',
                    axisLabel: {
                        formatter: '{value}'
                    },
                    splitLine: {
                        show: false
                    }
                },{
                    type: 'value',
                    axisLabel: {
                        formatter: '{value}'
                    },
                    splitLine: {
                        show: false
                    }
                }
                ],
                series:(function(){
                    var result=[];

                    result.push({
                        name: '总体',
                        type: 'line',
                        showSymbol: false,
                        hoverAnimation: false,
                        yAxisIndex:1,
                        data: (function(){
                            var data=[];

                            for(var i=0;i<servers.length;i++) {
                                var server=servers[i];
                                var serverInfo=getInfo(server.id,field);
                                if(data.length==0) {
                                    data=new Array(serverInfo.length);
                                }

                                for(var j=0;j<serverInfo.length;j++) {
                                    if(objectUtil.isNull(data[j])) {
                                        data[j]=0;
                                    }

                                    data[j]+=parseInt(serverInfo[j]);
                                }
                            }

                            return data;
                        })()
                    });

                    for(var i=0;i<servers.length;i++) {
                        var server=servers[i];
                        var runId=server.id;
                        var data=getInfo(runId,field);

                        result.push({
                            name: runId,
                            type: 'line',
                            showSymbol: false,
                            hoverAnimation: false,
                            data:data
                        });
                    }

                    return result;
                })()
            };

            return options;
        };

        var updateOpsChart=function(){
            $scope.opsChartOptions=getChartOptions('每秒操作数','instantaneous_ops_per_sec');
        };

        var updateConnectChart=function(){
            $scope.connectChartOptions=getChartOptions('连接数','connected_clients');
        };

        var updateRejectedConnectChart=function(){
            $scope.rejectedConnectChartOptions=getChartOptions('拒绝连接数','rejected_connections');
        };

        var updateTotalConnectReceivedChart=function(){
            $scope.totalConnectReceivedChartOptions=getChartOptions('处理连接数','total_connections_received');
        };

        var updateTotalCommandProcessedChart=function(){
            $scope.totalCommandProcessedChartOptions=getChartOptions('处理命令数','total_commands_processed');
        };

        var updateClientLongestOutputListInSecondChart=function(){
            $scope.clientLongestOutputListInSecondOptions=getChartOptions('每秒输出字节','client_longest_output_list_in_seconds');
        };

        var updateClientLongestInputBufInSecondChart=function(){
            $scope.clientLongestInputBufInSecondOptions=getChartOptions('每秒输入字节','client_longest_input_buf_in_seconds');
        };

        var updateConnectTimeoutChart=function(){
            $scope.connectTimeoutOptions=getChartOptions('每秒超时','connect_timeout');
        };

        var updateConnectTimeoutInSecondChart=function(){
            $scope.connectTimeoutInSecondOptions=getChartOptions('所有超时','connect_timeout_in_seconds');
        };

        var intervalFunction=function(){
            updateInfoMap(function(){
                updateOpsChart();
                updateConnectChart();
                updateRejectedConnectChart();
                updateTotalCommandProcessedChart();
                updateTotalConnectReceivedChart();
                updateClientLongestOutputListInSecondChart();
                updateClientLongestInputBufInSecondChart();
                updateConnectTimeoutChart();
                updateConnectTimeoutInSecondChart();
            });
        };

        var interval=setInterval(function(){
            intervalFunction();
        },1000*1);

        $rootScope.$on('$locationChangeStart', function(){
            clearInterval(interval);
        });

        intervalFunction();
    });
}]);